package com.ruoyi.system.service.impl;

import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.system.domain.vo.FeedBackVo;
import com.ruoyi.system.domain.vo.MessageVo;
import com.ruoyi.system.service.MessageService;
import io.jsonwebtoken.lang.Collections;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import static com.ruoyi.common.utils.DateUtils.YYYY_MM_DD_HH_MM_SS;

/**
 * @author Yuan
 * @description 消息处理
 * @date 2023/12/5
 */
@Service
@RequiredArgsConstructor
public class MessageServiceImpl implements MessageService {
    private final RedisCache redisCache;

    @Override
    public void feedBack(String carId, MessageVo messageVo) {
        String key = CacheConstants.AFTER_SALES_EVALUATION + carId;
        //查询出最新的三条记录，判断是否有商家留言____防刁民
        List<MessageVo> messages = redisCache.lrange(key, -3, -1);
        if(messages != null && messages.size() == 3) {
            boolean isReply = false; //商家是否有回复标识
                for (MessageVo message : messages) {
                if("merchant".equals(message.getSender())){
                    isReply = true;
                    break;
                }
            }
            //商家未恢复情况，后端处理，防刁民
            if(!isReply) {
                //三条消息中未有商家回复信息，避免Postman攻击系统
                throw new ServiceException("商家未回复之前, 您只可发送三条信息");
            }
        }

        //获取当前value的权重
        Double score = redisCache.getScore(CacheConstants.NO_REPLY_MSG_COUNT, carId);
        if(score == null) {
            //新增
            redisCache.setScore(CacheConstants.NO_REPLY_MSG_COUNT, carId, 1);
        }else{
            //修改
            redisCache.updateScore(CacheConstants.NO_REPLY_MSG_COUNT, carId, 1);
        }
        messageVo.setId(IdUtils.fastSimpleUUID());
        //设置创建时间
        messageVo.setCreateTime(DateUtils.dateTimeNow(YYYY_MM_DD_HH_MM_SS));
        List<MessageVo> list = new ArrayList<>(1);
        list.add(messageVo);
        // 保存消息到列表中
        redisCache.setCacheList(key, list);
    }

    @Override
    public AjaxResult getMessages(String carId, long index) {
        String key = CacheConstants.AFTER_SALES_EVALUATION + carId;
        // 获取车辆ID对应最新100条数据
        List<MessageVo> messages = redisCache.lrange(key, -99+index, index);
        return AjaxResult.success(messages);
    }

    /**
     * 根据反馈信息
     * @return
     */
    @Override
    public AjaxResult getFeedBackLastMessage(String carId, int pageNum, int pageSize) {
        List<FeedBackVo> feedBackVoList = new ArrayList<>();
        if(carId != null) {
            String key = CacheConstants.AFTER_SALES_EVALUATION + carId;
            // 获取车辆ID对应最新数据
            getFeedBackInfo(key, feedBackVoList);
        }else{
            //在权重表中进行排序
            Set<String> carIds = redisCache.getValuesByScoreDesc(CacheConstants.NO_REPLY_MSG_COUNT, pageNum, pageSize);
            for (String item : carIds) {
                // 获取车辆ID对应最新数据
                getFeedBackInfo(CacheConstants.AFTER_SALES_EVALUATION + item, feedBackVoList);
            }
        }
        return AjaxResult.success(feedBackVoList);
    }

    @Override
    public AjaxResult getFeedBackCount(){
        return AjaxResult.success(redisCache.getCountByPrefix(CacheConstants.AFTER_SALES_EVALUATION));
    }

    @Override
    public AjaxResult removeFeedBack(String carId) {
        if(StringUtils.isEmpty(carId)){
            return AjaxResult.error("删除失败,请重新刷新页面");
        }
        String key = CacheConstants.AFTER_SALES_EVALUATION + carId;
        boolean b = redisCache.deleteObject(key);
        return b ? AjaxResult.success("删除成功"):AjaxResult.error("删除失败");
    }

    //PC端回复
    @Override
    public void reply(String carId, MessageVo messageVo) {
        String key = CacheConstants.AFTER_SALES_EVALUATION + carId;
        Double score = redisCache.getScore(CacheConstants.NO_REPLY_MSG_COUNT, carId);
        //判断是否已读
        if(score==1.0){
            //修改
            redisCache.updateScore(CacheConstants.NO_REPLY_MSG_COUNT, carId, 0);
        }
        messageVo.setId(IdUtils.fastSimpleUUID());
        //设置创建时间
        messageVo.setCreateTime(DateUtils.dateTimeNow(YYYY_MM_DD_HH_MM_SS));
        List<MessageVo> list = new ArrayList<>(1);
        list.add(messageVo);
        // 保存消息到列表中
        redisCache.setCacheList(key, list);
    }

    private void getFeedBackInfo(String key, List<FeedBackVo> feedBackVoList) {
        List<MessageVo> list = redisCache.lrange(key, -3, -1);
        if(list != null && list.size() > 0){
            String carId = key.substring(CacheConstants.AFTER_SALES_EVALUATION.length());
            MessageVo messageVo = list.get(list.size() - 1);
            FeedBackVo feedBackVo = new FeedBackVo();
            BeanUtils.copyBeanProp(feedBackVo,messageVo);
            long count = countUnreadMessagesBeforeMerchant(list);
            feedBackVo.setUnreadMsgCount(count);
            feedBackVo.setCarId(carId);
            feedBackVoList.add(feedBackVo);
        }
    }

    //计算未读消息个数
    private long countUnreadMessagesBeforeMerchant(List<MessageVo> messages) {
        long count = 0;
        // 从后往前遍历
        for (int i = messages.size() - 1; i >= 0; i--) {
            MessageVo message = messages.get(i);
            // 判断 sender 是否为 "merchant"
            if ("merchant".equals(message.getSender())) {
                break;  // 遇到 "merchant" 就停止遍历
            }
            count++;
        }
        return count;
    }


}